package com.pro.common.service.user.service;

import com.pro.common.api.model.dto.UserAmountDTO;
import com.pro.common.api.model.dto.UserAmountKey;
import com.pro.common.api.user.intf.UserFeignClient;
import com.pro.common.api.user.model.db.User;
import com.pro.common.api.user.model.db.UserAmount;
import com.pro.common.service.model.mapstruct.UserModelMapper;
import com.pro.common.service.user.dao.UserAmountDao;
import com.pro.framework.api.util.CollUtils;
import com.pro.framework.mybatisplus.BaseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * ${label}服务
 */
@Service
@Slf4j
@AllArgsConstructor
public class UserAmountService extends BaseService<UserAmountDao, UserAmount> {
    private UserFeignClient<? extends User> userFeignClient;
    private UserModelMapper userModelMapper;


    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateUserAmountDTO(List<UserAmountDTO> userAmountDTOS) {
        if (userAmountDTOS.isEmpty()) {
            return;
        }
        List<Long> userIds = userAmountDTOS.stream().map(UserAmountDTO::getUserId).toList();
        Map<Long, ? extends User> userMap = userFeignClient.idMap(userIds);
        Map<UserAmountKey, UserAmount> oldMap = CollUtils.listToMap(lambdaQuery().in(UserAmount::getUserId, userIds).list(), UserAmount::toKey);
//        this.lambdaQuery().in(UserStorage::getUserId, userIds).list();
        this.saveOrUpdateBatch(userAmountDTOS.stream().map(dto -> {
            UserAmount entity = new UserAmount();
            UserAmount old = oldMap.get(dto.toKey());
            if (old == null) {
                User user = userMap.get(dto.getUserId());
                userModelMapper.copy(user, entity);
//                userStorage.setRemark("");
//                userStorage.setAmountType(0);
//                userStorage.setTodayIncreaseAmount(new BigDecimal(0));
//                userStorage.setTotalIncreaseAmount(new BigDecimal(0));
                entity.setAmountType(dto.getAmountType());
            } else {
                entity.setId(old.getId());
            }

            entity.setTotalAmount(dto.getAmount());
//            userStorage.setAmount(new BigDecimal(0));
            return entity;
        }).toList());
    }

    public BigDecimal getTotalAmount(Long userId, String amountType) {
        UserAmount param = new UserAmount();
        param.setUserId(userId);
        param.setAmountType(amountType);
        UserAmount one = getOne(param);
        return null == one ? BigDecimal.ZERO : one.getTotalAmount();
    }
}
